import requests
from fake_useragent import UserAgent
import os
from bs4 import BeautifulSoup
import re
from tqdm import tqdm

url="https://github.com/2dust/v2rayN/releases"
headers = {
    "User-Agent": UserAgent().random,
    "Referer": "https://github.com/2dust/v2rayN/releases",  # 设置防盗链
}
html=requests.get(url=url,headers=headers)

soup = BeautifulSoup(html.content, 'html.parser')
h2_tags = soup.find_all('h2', {'class': 'sr-only', 'id': True})
print("V2rayn最新版本："+h2_tags[0].text)
url1="https://github.com/2dust/v2rayN/releases/expanded_assets/{}".format(h2_tags[0].text)
print("最新下载地址："+url1)

html1=requests.get(url=url1,headers=headers)
a=re.findall(r'<a href="(.*?)" rel',html1.text)
urls=[]
for i in a:
    if "Core-SelfContained" in i:  # 修改此处变量为 i
        print(f"https://github.com{i}")
        urls.append(f"https://github.com{i}")

x = int(input("下载最新安装包版本请输入 0\n不下载请输入其他数字（1 或其他非 0 ）\n你的输入是："))
def download_file(ur, filename, html2):
    try:
        total_size = int(html2.headers.get('content-length', 0))
        chunk_size = 1024  # 每次下载的块大小，可以根据需要调整
        downloaded_size = 0

        with open(f"D:/360安全浏览器下载/{filename}", 'wb') as f:
            for chunk in tqdm(html2.iter_content(chunk_size=chunk_size), total=total_size//chunk_size, unit='KB', desc=filename, unit_scale=True):
                if chunk:
                    f.write(chunk)
                    downloaded_size += len(chunk)
        
        print(f"\n文件从 {ur} 下载成功到 D:/360安全浏览器下载/{filename}")
    except Exception as e:
        print(f"下载 {ur} 失败：{e}")

try:
    if x == 0:
        # print(urls[x])  # 打印实际使用的下载链接
        html2 = requests.get(url=urls[x])
        # print(html2.status_code)
        if html2.status_code == 200:
            ur = urls[0]  # 修正为 ur = urls[x]
            filename = f"V2rayn {h2_tags[0].text}安装包.7z"
            download_file(ur, filename, html2)
        else:
            print(f"下载 {urls[x]} 失败：请求状态码 {html2.status_code}")
    else:
        print("已取消下载，输入不在可选范围内。")
except ValueError:
    print("输入无效，请输入一个数字。")
except Exception as e:
    print(f"下载失败：{e}")
